package com.vhall.component.service.record.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vhall.component.dao.record.RecordMapper;
import com.vhall.component.entity.record.RecordEntity;
import com.vhall.component.entity.record.RecordEntityCacheDTO;
import com.vhall.component.entity.record.RecordEntityDTO;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.service.record.RecordInnerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author lsl
 * @since 2021/6/9
 */
@Service
public class RecordInnerServiceImpl implements RecordInnerService {

    @Autowired
    private RecordMapper recordMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public RecordEntityDTO getRecord(String recordId) {
        RecordEntityDTO dto = new RecordEntityDTO();
        LambdaQueryWrapper<RecordEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RecordEntity::getVodId, recordId);
        wrapper.orderByDesc(RecordEntity::getUpdatedAt);
        wrapper.last(" limit 1 ");
        RecordEntity entity = recordMapper.selectOne(wrapper);
        if (entity != null) {
            BeanUtils.copyProperties(entity, dto);
        }
        return dto;
    }

    @Override
    public RecordEntityCacheDTO getCacheRecord(String recordId) {
        String key = RedisKey.RECORD_INFO_ID + recordId;
        RecordEntityCacheDTO result = null;
        if (redisTemplate.hasKey(key)) {
            result = (RecordEntityCacheDTO) redisTemplate.opsForValue().get(key);
        }else{
            RecordEntityDTO record = getRecord(recordId);
            RecordEntityCacheDTO temp = new RecordEntityCacheDTO();
            BeanUtil.copyProperties(record,temp);
            redisTemplate.opsForValue().set(key,temp,100, TimeUnit.SECONDS);
        }
        return result;
    }
}
